import asyncio
import json

from okx.websocket.WsPublicAsync import WsPublicAsync
from sortedcontainers import SortedList


# Define a key function that sorts by the negative of the first element
def sort_key(item):
    # Assumes the first element of the item can be converted to a float
    return -float(item[0])
# Create a SortedList with the key function
asks_sorted = SortedList(key=sort_key)
bids_sorted = SortedList(key=sort_key)
def publicCallback(message):
    # 添加数据
    # print(message)
    if 'data' in message:
        json_data = json.loads(message)
        print(json_data['data'][0]['markPx'])


async def main():
    # url = "wss://wspap.okex.com:8443/ws/v5/public?brokerId=9999"
    url = "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"
    ws = WsPublicAsync(url=url)
    await ws.start()
    args = []
    # arg1 = {"channel": "books-grouped", "grouping": "0.01", "instType": "SPOT", "instId": "ETH-USDT"}
    # arg2 = {"channel": "books5", "instId":"ETH-USDT" , "action": "snapshot"}
    arg2 = {"channel": "mark-price", "instType": "SPOT", "instId":"ETH-USDT" ,}
    # arg3 = {"channel": "tickers", "instId": "BTC-USDT-SWAP"}
    # arg4 = {"channel": "tickers", "instId": "ETH-USDT"}
    # args.append(arg1)
    args.append(arg2)
    # args.append(arg3)
    # args.append(arg4)
    await ws.subscribe(args, publicCallback)
    await asyncio.sleep(1000)
    # print("-----------------------------------------unsubscribe--------------------------------------------")
    # args2 = [arg4]
    # await ws.unsubscribe(args2, publicCallback)
    # await asyncio.sleep(5)
    # print("-----------------------------------------unsubscribe all--------------------------------------------")
    # args3 = [arg1, arg2, arg3]
    # await ws.unsubscribe(args3, publicCallback)


if __name__ == '__main__':
    asyncio.run(main())